package middleware

import (
	"github.com/gogf/gf/v2/net/ghttp"
	"goAdminV1/utility"
)

type Paginated interface {
	GetLimit() int
	GetTotal() int
	GetData() interface{}
}

func ResponseWrapper(r *ghttp.Request) {
	r.Middleware.Next()

	// 错误处理
	if err := r.GetError(); err != nil {
		code := utility.Code(err)
		r.Response.WriteJson(utility.Response{
			Code:    code,
			Message: err.Error(),
			Data:    nil,
		})
		return
	}

	// 成功处理
	resp := r.GetHandlerResponse()
	switch v := resp.(type) {
	case utility.PaginatedResponse:
		r.Response.WriteJson(v)
	case Paginated:
		r.Response.WriteJson(utility.SuccessWithPagination(
			v.GetData(),
			v.GetLimit(),
			v.GetTotal(),
		))
	default:
		r.Response.WriteJson(utility.Success(v))
	}
}
